package com.justgame.project.service.just.service;

import com.justgame.project.cloud.common.exception.Exc;
import com.justgame.project.cloud.common.util.ObjUtil;
import com.justgame.project.cloud.common.util.ShiroUtils;
import com.justgame.project.cloud.common.entity.PageRequest;
import com.justgame.project.service.api.dto.JustGameCloudDTO;
import com.justgame.project.service.api.entity.JustGameCloud;
import com.justgame.project.service.api.feign.ISysStationOrderClient;
import com.justgame.project.service.api.vo.JustGameCloudVO;
import com.justgame.project.service.api.vo.JustGameInfoVO;
import com.justgame.project.service.just.mapper.JustGameCloudMapper;
import com.justgame.project.service.just.mapper.JustGameInfoMapper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Transactional(rollbackFor = Exception.class)
@AllArgsConstructor
public class JustGameCloudService {
    private final JustGameInfoMapper gameInfoMapper;
    private final JustGameCloudMapper gameCloudMapper;
    private final ISysStationOrderClient sysStationOrderClient;


    public PageRequest<JustGameCloud> getList(PageRequest pageRequest, JustGameCloudDTO dto) {
        pageRequest.startPage();
        return pageRequest.BuildPageInfo(gameCloudMapper.getList(dto));
    }

    public Boolean save(JustGameCloudDTO dto) {
        ObjUtil.inject(dto, true);
        return gameCloudMapper.Insert(dto) > 0;
    }

    public Boolean Delete(JustGameCloudDTO dto) {
        if (dto.getIds() == null || dto.getIds().size() == 0) {
            throw new Exc("请先选择你要删除的数据！");
        }
        ObjUtil.inject(dto, false);
        return gameCloudMapper.Delete(dto) > 0;
    }

    public Boolean updateById(JustGameCloudDTO dto) {
        if (!ObjUtil.checkId(dto)) throw new Exc("请重新选择后再试！");
        ObjUtil.inject(dto, false);
        return gameCloudMapper.UpdateById(dto) > 0;
    }

    public List<JustGameCloudVO> obtainResourceByGid(String gameId) {
        String userId = ShiroUtils.getUserId();
        if (StringUtils.isBlank(userId)) {
            throw new Exc("请登录后重试！");
        }
        JustGameInfoVO gameInfo = gameInfoMapper.SelectById(gameId);
        /* 判断游戏是否存在 */
        if (gameInfo == null){
            throw new Exc("该游戏不存在，请刷新后重试！");
        }
        /* 判断游戏是否需付费 */
        if (gameInfo.getCost() != null && gameInfo.getCost() > 0){
            /* 查询订单是否已购买该游戏 */
            if (!sysStationOrderClient.hasBought(userId, gameId)) {
                throw new Exc("您还未购买该游戏哦！");
            }
        }
        /* 构建查询条件 */
        JustGameCloudDTO selectDto = new JustGameCloudDTO();
        selectDto.setGameInfoId(gameId);
        return gameCloudMapper.getList(selectDto);
    }
}
